<?php
namespace frontend\controllers;

use common\components\FrontBaseController;
use Yii;
use \common\helps\tools;
use \common\helps\code;
use yii\db\Query;

/**
 * User controller
 */
class WealController extends FrontBaseController
{

    public $modelClass = 'frontend\models\Weal';
    public function init()
    {
        parent::init();
    }

    /*
     * 任务列表
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionTaskList(){
        $model = new \frontend\models\Task();
        $member = new \frontend\models\Member();
        $request =$this->request;
        $params = $request->bodyParams;
        $redis = Yii::$app->cache;
        $member_info = $this->member_info;
        $member_data = $member::findOne(['id' => $member_info['id']]);

        $total = $model::selectFieldData([],'*');
        $res = tools::getPageData($total,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        foreach ($res['data'] as $k => $v){
            $row1 = $redis->get('signIn'.$member_info['id'].'/'.date('Y-m-d'));
            $row2 = $redis->get('checkPosts'.date('Y-m-d').$member_info['id']);
            $row3 = $redis->get('checkComment'.date('Y-m-d').$member_info['id']);
            $row4 = $redis->get('dayClick'.date('Y-m-d').$member_info['id'].'like');
            $row5 = $redis->get('dayClick'.date('Y-m-d').$member_info['id'].'collect');
            $row6 = $redis->get('watchVideo'.date('Y-m-d').$member_info['id']);
            $row7 = $redis->get('shareWeChart'.date('Y-m-d').$member_info['id']);
            $row8 = $redis->get('watchGuide'.$member_info['id']);
            $row9 = empty($member_data['is_first_edit'])?'':$member_data['is_first_edit'];


            if($v['id'] == 1 && !empty($row1)){
                $res['data'][$k]['status'] = 3;//表示任务已完成
            }
            if($v['id'] == 2 && !empty($row2)){
                $res['data'][$k]['status'] = 3;//表示任务已完成
            }
            if($v['id'] == 3 && !empty($row3)){
                $res['data'][$k]['status'] = 3;//表示任务已完成
            }
            if($v['id'] == 4 && !empty($row4)){
                $res['data'][$k]['status'] = 3;//表示任务已完成
            }
            if($v['id'] == 5 && !empty($row5)){
                $res['data'][$k]['status'] = 3;//表示任务已完成
            }
            if($v['id'] == 6 && !empty($row6)){
                $res['data'][$k]['status'] = 3;//表示任务已完成
            }
            if($v['id'] == 7 && !empty($row7)){
                $res['data'][$k]['status'] = 3;//表示任务已完成
            }
            if($v['id'] == 8 && !empty($row8)){
                $res['data'][$k]['status'] = 3;//表示任务已完成
            }
            if($v['id'] == 9 && !empty($row9)){
                $res['data'][$k]['status'] = 3;//表示任务已完成
            }

            $res['data'][$k]['created_at'] = date('Y-m-d H:i:s',$v['created_at']);
        }
        return code::success($res);
    }

    /*
     * 福利列表
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionWealList(){
        $model = new \frontend\models\Weal();
        $request =$this->request;
        $params = $request->bodyParams;
        //$params = $request->queryParams;

        $total = $model::selectFieldData(['status' => 1],'*');
        $res = tools::getPageData($total,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        foreach ($res['data'] as $k => $v){
            $res['data'][$k]['created_at'] = date('Y-m-d H:i:s',$v['created_at']);
        }
        return code::success($res);
    }

    /*
     * 福利详情
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionWealDetail()
    {
        $model = new \frontend\models\Weal();
        $request =$this->request;
        $params = $request->bodyParams;

        $res = $model::findData($params,'*');
        return code::success($res);
    }

    /*
     * 福利兑换
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionWealExchange()
    {
        $model = new \frontend\models\WealExchange();
        $weal = new \frontend\models\Weal();
        $member = new \frontend\models\Member();
        $int = new \frontend\models\IntLog();
        $redis = Yii::$app->cache;
        $request =$this->request;
        $params = $request->bodyParams;
        $member_info = $this->member_info;

        if(empty($params['weal_id']))
            return code::error('mistake');
        $res = $weal::findOneData(['id' => $params['weal_id'],'status' => 1]);
        if(empty($res)){
            return code::error('mistake');
        }
        if($res['num'] <= 0){
            return code::error('','该商品已兑完');
        }
        if($member_info['integral'] < $res['integral']){
            return code::error('','积分不满足兑换条件，请继续努力');
        }
        $data = [
            'member_id' => $member_info['id'],
            'weal_id' => $res['id'],
            //'order_num ' => tools::createOrderNo('W'),
            'weal_title' => $res['title'],
        ];
        $data['order_num'] = tools::createOrderNo('W');
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $success = $model::addData($data);
            $integral = $member_info['integral'] - $res['integral'];
            $row = $member::saveData($member_info['id'],['integral' => $integral]);
            $idata = [
                'member_id' => $member_info['id'],
                'weal_id' => $res['id'],
                'int' => $res['integral'],
                'type' => 2,
                'mark' => $res['title'],
            ];
            $rat = $int::addData($idata);

            $cut = $weal::cutNum($params['weal_id']);

            $member_info['integral'] = $integral;
            $redis->hset('member_info', $member_info['token'], json_encode($member_info));
            if($success && $row && $rat && $cut){
                $transaction->commit();
                return code::success('true');
            }else{
                return code::error('error');
            }
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /*
     * 我的福利
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionMyWeal(){
        $model = new \frontend\models\WealExchange();
        $request =$this->request;
        $params = $request->bodyParams;
        $member_info = $this->member_info;

        $total = $model::selectFieldData(['member_id' => $member_info['id'],'type' => 1],'`title`,`thumb`,`order_num`,`mark`,`weal_exchange`.`status`');
        $res = tools::getPageData($total,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        return code::success($res);
    }

    /*
     * 积分列表
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionIntList(){
        $model = new \frontend\models\IntLog();
        $weal = new \frontend\models\Weal();
        $task = new \frontend\models\Task();
        $request =$this->request;
        $params = $request->bodyParams;
        $member_info = $this->member_info;

        $data = [
            'member_id' => $member_info['id'],
        ];
        if(!empty($params['type'])){
            $data['type'] = $params['type'];
        }
        $total = $model::selectFieldData($data);
        $res = tools::getPageData($total,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        foreach ($res['data'] as $k => $v){
            if(empty($v['task_id'])){
                $row = $weal::findData(['id' => $v['weal_id']]);
            }else{
                $row = $task::findOne(['id' => $v['task_id']]);
            }
            $res['data'][$k]['title'] = $row['title'];
        }
        return code::success($res);
    }

    /*
     * 我的积分
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionMyInt()
    {
        $member_info = $this->member_info;
        $model = new \frontend\models\IntLog();

        $res['int'] = $member_info['integral'];
        $get_int = $model::selectSumData(['member_id' => $member_info['id'],'type' => 1],'sum(`int`)');
        $use_int = $model::selectSumData(['member_id' => $member_info['id'],'type' => 2],'sum(`int`)');
        $res['get_int'] = empty($get_int[0]['sum(`int`)'])?0:$get_int[0]['sum(`int`)'];
        $res['use_int'] = empty($use_int[0]['sum(`int`)'])?0:$use_int[0]['sum(`int`)'];
        return code::success($res);
    }

    /*
     * 签到展示（连续签到）
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionSignAll(){
        $model = new \frontend\models\Task();
        $redis = Yii::$app->cache;
        $member_info = $this->member_info;

        $row = $model::findOne(['id' => 1]);
        $rat = $redis->get('signIn'.$member_info['id'].'/'.date('Y-m-d',time()-86400*3));
        $res[0]['sign'] = empty($rat)?'no':'yes';
        $res[0]['int'] = $row['integral'];
        if(empty($rat)){
            $res[0]['date'] = date('m-d',time()-86400*3);
        }else{
            $res[0]['date'] = date('m-d',$rat);
        }


        $rat = $redis->get('signIn'.$member_info['id'].'/'.date('Y-m-d',time()-86400*2));
        $res[1]['sign'] = empty($rat)?'no':'yes';
        $res[1]['int'] = $row['integral'];
        if(empty($rat)){
            $res[1]['date'] = date('m-d',time()-86400*2);
        }else{
            $res[1]['date'] = date('m-d',$rat);
        }

        $rat = $redis->get('signIn'.$member_info['id'].'/'.date('Y-m-d',time()-86400*1));
        $res[2]['sign'] = empty($rat)?'no':'yes';
        $res[2]['int'] = $row['integral'];
        if(empty($rat)){
            $res[2]['date'] = date('m-d',time()-86400*1);
        }else{
            $res[2]['date'] = date('m-d',$rat);
        }

        $rat = $redis->get('signIn'.$member_info['id'].'/'.date('Y-m-d'));
        $res[3]['sign'] = empty($rat)?'no':'yes';
        $res[3]['int'] = $row['integral'];
        if(empty($rat)){
            $res[3]['date'] = date('m-d',time());
        }else{
            $res[3]['date'] = date('m-d',$rat);
        }

        $res[4]['sign'] = 'no';
        $res[4]['int'] = $row['integral'];
        $res[4]['date'] = date('m-d',time()+86400);

        $res[5]['sign'] = 'no';
        $res[5]['int'] = $row['integral'];
        $res[5]['date'] = date('m-d',time()+86400*2);

        $res[6]['sign'] = 'no';
        $res[6]['int'] = $row['integral'];
        $res[6]['date'] = date('m-d',time()+86400*3);

        $total = $redis->get('totalSignIn'.$member_info['id']);
        $sign_in = $redis->get('signIn'.$member_info['id'].'/'.date('Y-m-d'));
        $data['total'] = empty($total)?0:$total;
        $data['is_sign'] = empty($sign_in)?'no':'yes';
        $data['list'] = $res;
        return code::success($data);
    }

    /*
     * 签到
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionSignIn(){
        $model = new \frontend\models\Task();
        $member = new \frontend\models\Member();
        $int = new \frontend\models\IntLog();
        $redis = Yii::$app->cache;
        $request =$this->request;
        $params = $request->bodyParams;
        $member_info = $this->member_info;

        $res = $model::findOne(['id' => 1]);
        $sign_in = $redis->get('signIn'.$member_info['id'].'/'.date('Y-m-d'));
        if($sign_in === false){
            $redis->set('signIn'.$member_info['id'].'/'.date('Y-m-d'),time());
        }else{
            return code::error('','今日已签到');
        }
        $yesterday = $redis->get('signIn'.$member_info['id'].'/'.date('Y-m-d',time()-86400));
        if(!empty($yesterday)){
            $total = $redis->get('totalSignIn'.$member_info['id']);
            if($total === false){
                $total = 0;
            }
            $redis->set('totalSignIn'.$member_info['id'],$total+1);
        }else{
            $redis->set('totalSignIn'.$member_info['id'],1);
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $integral = $member_info['integral'] + $res['integral'];
            $row = $member::saveData($member_info['id'],['integral' => $integral]);
            $idata = [
                'member_id' => $member_info['id'],
                'task_id' => $res['id'],
                'int' => $res['integral'],
                'type' => 1,
                'mark' => $res['title'],
            ];
            $rat = $int::addData($idata);
            $member_info['integral'] = $integral;
            $redis->hset('member_info', $member_info['token'], json_encode($member_info));
            if($row && $rat){
                $transaction->commit();
                return code::success('true');
            }else{
                return code::error('error');
            }
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /*
     * 看视频
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionWatchVideo(){
        $task = new \frontend\models\Task();
        $member = new \frontend\models\Member();
        $int = new \frontend\models\IntLog();
        $redis = Yii::$app->cache;
        $member_info = $this->member_info;

        $day = $redis->get('watchVideo'.date('Y-m-d').$member_info['id']);
        if($day === false){
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $task_info = $task::findOne(['id' => 6]);
                $idata = [
                    'member_id' => $member_info['id'],
                    'task_id' => $task_info['id'],
                    'int' => $task_info['integral'],
                    'type' => 1,
                ];
                $intLog = $int::addData($idata);

                $integral = $member_info['integral'] + $task_info['integral'];
                $addInt = $member::saveData($member_info['id'],['integral' => $integral]);
                $member_info['integral'] = $integral;
                $redis->hset('member_info', $member_info['token'], json_encode($member_info));
                $redis->set('watchVideo' . date('Y-m-d') . $member_info['id'], date('Y-m-d H:i:s'),86400);
                if ($intLog && $addInt) {
                    $transaction->commit();
                    return code::success(['int' => $task_info['integral'],'is_watch' => 1]);
                }
            } catch (Exception $e) {
                $transaction->rollBack();
                return $e->getMessage();
            }
        }else{
            return code::success(['is_watch' => 2]);
        }
    }

    /*
     * 分享微信
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionShareWeChart(){
        $task = new \frontend\models\Task();
        $member = new \frontend\models\Member();
        $int = new \frontend\models\IntLog();
        $redis = Yii::$app->cache;
        $member_info = $this->member_info;

        $day = $redis->get('shareWeChart'.date('Y-m-d').$member_info['id']);
        if($day === false){
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $task_info = $task::findOne(['id' => 7]);
                $idata = [
                    'member_id' => $member_info['id'],
                    'task_id' => $task_info['id'],
                    'int' => $task_info['integral'],
                    'type' => 1,
                ];
                $intLog = $int::addData($idata);

                $integral = $member_info['integral'] + $task_info['integral'];
                $addInt = $member::saveData($member_info['id'],['integral' => $integral]);
                $member_info['integral'] = $integral;
                $redis->hset('member_info', $member_info['token'], json_encode($member_info));
                $redis->set('shareWeChart' . date('Y-m-d') . $member_info['id'], date('Y-m-d H:i:s'),86400);
                if ($intLog && $addInt) {
                    $transaction->commit();
                    return code::success(['int' => $task_info['integral'],'is_watch' => 1]);
                }
            } catch (Exception $e) {
                $transaction->rollBack();
                return $e->getMessage();
            }
        }else{
            return code::success(['is_watch' => 2]);
        }
    }

    /*
     * 观看操作指南
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionWatchGuide(){
        $task = new \frontend\models\Task();
        $member = new \frontend\models\Member();
        $int = new \frontend\models\IntLog();
        $redis = Yii::$app->cache;
        $member_info = $this->member_info;

        $day = $redis->get('watchGuide'.$member_info['id']);
        if($day === false){
            $confirm = $int::findOne(['member_id' => $member_info['id'],'task_id' => 8]);
            if(!empty($confirm)){
                return code::success([],'任务已完成');
            }
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $task_info = $task::findOne(['id' => 8]);
                $idata = [
                    'member_id' => $member_info['id'],
                    'task_id' => $task_info['id'],
                    'int' => $task_info['integral'],
                    'type' => 1,
                ];
                $intLog = $int::addData($idata);

                $integral = $member_info['integral'] + $task_info['integral'];
                $addInt = $member::saveData($member_info['id'],['integral' => $integral]);
                $member_info['integral'] = $integral;
                $redis->hset('member_info', $member_info['token'], json_encode($member_info));
                $redis->set('watchGuide' . $member_info['id'], date('Y-m-d H:i:s'));
                if ($intLog && $addInt) {
                    $transaction->commit();
                    return code::success(['int' => $task_info['integral'],'is_watch' => 1]);
                }
            } catch (Exception $e) {
                $transaction->rollBack();
                return $e->getMessage();
            }
        }else{
            return code::success(['is_watch' => 2]);
        }
    }


}
